package com.example.miniomultipartupload.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:  模拟前端分片上传
 * @author: konglingdi
 * @date: 2021/12/2 11:20
 */


public class PostUtils {

    public static void main(String[] args) {
        final ExecutorService executorService = Executors.newCachedThreadPool();
        List<String> urlList = Arrays.asList(
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_0",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_1",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_2",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_3",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_4",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_5",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_6",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_7",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_8",
                "/multipart/chunkUpload?uploadId=b3187a56-82bf-4c61-ae12-8937ecc88e15&chunk=chunk_9"
        );
        String prefix = "http://localhost:18089/dimensional";
        String auth = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImFiYzQ0MTg4LTNlYzktNDhmZi1iNDZhLTZlZDRkZDA4NDJjNSJ9.aCtC3plw1TY13VNB3QTGLN0o8FtvFJG4zxC5ICeRlpRgbIakkCvCyNhjOop9Y8cDNcG5Xz4cwSY2aguoC1GeFQ";
        for (int i = 0; i < urlList.size(); i++) {
            final int k = i;
            executorService.execute(() -> {
                long l = System.currentTimeMillis();
                put(auth, prefix, urlList.get(k), "C:\\Users\\15516\\Desktop\\三维\\qiege\\split" + k + ".split");
                long l1 = System.currentTimeMillis();
                System.out.println(l1 - l);
            });
        }

//        executorService.shutdown();
    }


    public static void put(String auth, String prefix, String url, String filePath) {
        putWithParams(auth, prefix, url, filePath);
    }

    private static void putWithParams(String auth, String prefix, String url, String filePath) {
            try {
                //构建HttpClient对象,此处主要是为了支持https请求，如若只是请求http，可通过HttpClients.createDefault();获取httpClient对象
                HttpClient client = HttpClients.createDefault();
                //CloseableHttpClient client = HttpClients.createDefault();
                //构建POST请求
                HttpPost httpPost = new HttpPost(prefix+url);
//                httpPost.setHeader("X-Atlassian-Token","nocheck");
                //此处设置的是confluence的账号密码，也可根据需求修改为设置cookies
                httpPost.setHeader("Authorization", auth);
//                httpPost.setConfig(setTimeOutConfig(httpPost.getConfig()));

                //要上传的文件
                File file = new File(filePath);
                //构建文件体
                FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);

                HttpEntity httpEntity = MultipartEntityBuilder
                        .create()
                        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                        .addPart("file", fileBody).build();
                httpPost.setEntity(httpEntity);
                //发送请求
                HttpResponse response = client.execute(httpPost);
                httpEntity = response.getEntity();
                if (httpEntity != null && response.getStatusLine().getStatusCode() != 200) {
//                    throw new WikiClientException("客户端请求失败！");
                }
            System.out.println(">>>>>>>>>>>>>>" + filePath + "的响应状态为:" + response.getStatusLine().getStatusCode());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }


    public void post(String url) {
        postWithParams(url, new HashMap<>());
    }

    public void postWithParams(String url, Map<String, String> params) {
        List<NameValuePair> pairs = generatePairs(params);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectTimeout(2000) //连接服务器超时时间
                    .build();
            httpPost.setConfig(requestConfig);

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 由客户端执行(发送)请求
            response = httpClient.execute(httpPost);
            System.out.println("响应状态为:" + response.getStatusLine());
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private List<NameValuePair> generatePairs(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return Collections.emptyList();
        }

        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (key == null) {
                continue;
            }

            pairs.add(new BasicNameValuePair(key, value));
        }

        return pairs;
    }


    public static String httpClientUploadFile(String url, File file) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
//每个post参数之间的分隔。随意设定，只要不会和其他的字符串重复即可。
        String boundary = "--------------4585696313564699";
        try {
            //文件名
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

            //HttpEntity builder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //字符编码
            builder.setCharset(Charset.forName("UTF-8"));
            //模拟浏览器
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            //boundary
            builder.setBoundary(boundary);
            //multipart/form-data
            builder.addPart("file", new FileBody(file, ContentType.DEFAULT_BINARY));
            // binary
            //builder.addBinaryBody("name=\"file\"; filename=\"mysql.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            //其他参数
            //builder.addTextBody("file_name", fileName, ContentType.create("text/plain", Consts.UTF_8));
            builder.addTextBody("file_name", fileName, ContentType.MULTIPART_FORM_DATA);
            builder.addTextBody("file_code", "111111", ContentType.MULTIPART_FORM_DATA);
            //HttpEntity
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            //响应
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("result" + result);
        return result;
    }

    //main 方法
    public static void main1(String[] args) {
        httpClientUploadFile("http://localhost:8080/dimensional/multipart/chunkUpload?uploadId=447edc77-ba9d-41e3-974c-a1823d0fc573&chunk=chunk_0", new File("C:\\Users\\15516\\Desktop\\multi\\split0.split"));
    }

}

